//
//  BussinessModel.m
//  OneCard
//
//  Created by sally on 16/2/17.
//  Copyright © 2016年 koalac. All rights reserved.
//


#import "BussinessModel.h"
#import "UIImageView+WebCache.h"
#import "SDWebImageManager.h"
#import "ApiBase.h"
#import <objc/runtime.h>

static NSError *_lastError = nil;

@implementation BussinessModel

- (instancetype)initWithJsonObject:(id)jsonObject {
  self = [super init];

  if (self) {
  }

  return self;
}

+ (void)setLastError:(NSError *)error {
  _lastError = error;
}

+ (NSError *)getLastError {
  return _lastError;
}

+ (void)cleanLastError {
  _lastError = nil;
}

- (void)setLastError:(NSError *)error {
  [self.class setLastError:error];
}

- (NSError *)getLastError {
  return [self.class getLastError];
}

- (void)cleanLastError {
  [self.class cleanLastError];
}

+ (NSDictionary *)getObjectData:(id)obj {
  NSMutableDictionary *dic = [NSMutableDictionary dictionary];
  unsigned int propsCount;
  objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
  for (int i = 0; i < propsCount; i++) {
    objc_property_t prop = props[i];

    NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
    id value = [obj valueForKey:propName];
    if (value == nil || [value isKindOfClass:[NSNull class]]) {
      value = @""; //[NSNull null];
    } else {
      value = [self getObjectInternal:value];
    }
    [dic setObject:value forKey:propName];
  }
  return dic;
}

+ (id)getObjectInternal:(id)obj {
  if ([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]] || [obj isKindOfClass:[NSNull class]]) {
    return obj;
  }

  if ([obj isKindOfClass:[NSArray class]]) {
    NSArray *objarr = obj;
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
    for (int i = 0; i < objarr.count; i++) {
      [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
    }
    return arr;
  }

  if ([obj isKindOfClass:[NSDictionary class]]) {
    NSDictionary *objdic = obj;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
    for (NSString *key in objdic.allKeys) {
      [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
    }
    return dic;
  }
  return [self getObjectData:obj];
}

/**
 *  替换url的域名
 *  @param urlStr 传入url
 *  @return 替换域名后的url
 */
+ (NSString *)replaceUrlDomain:(NSString *)urlStr {
  NSURL *url = [[NSURL alloc] initWithString:urlStr];
  NSString *host = [NSString stringWithFormat:@"%@", [ApiBase shareInstance].host];
  NSRange range = [urlStr rangeOfString:@"http"];
  if (range.length > 0) {
    NSURL *replacedUrl = [[NSURL alloc] initWithScheme:url.scheme host:host path:url.path];
    return [replacedUrl absoluteString];
  } else {
    return urlStr;
  }
}

+ (UIImageView *)getImageForView:(UIImageView *)imageView andImageURL:(NSString *)url {
  UIImageView *setImageView = imageView;
  setImageView.backgroundColor = [UIColor whiteColor];
  if (setImageView) {
    __block UIActivityIndicatorView *activityIndicator;
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    [manager downloadImageWithURL:[NSURL URLWithString:url] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
      if (!activityIndicator)
      {
        [setImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
        setImageView.backgroundColor = [UIColor whiteColor];
        activityIndicator.center = imageView.center;
        [activityIndicator startAnimating];
      }
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
      [activityIndicator stopAnimating];
      [activityIndicator setHidesWhenStopped:YES];
      [activityIndicator setHidden:YES];
      setImageView.image = image;
    }];
  }
  return setImageView;
}

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
  if (jsonString == nil) {
    return nil;
  }

  NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  NSError *err;
  NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                      options:NSJSONReadingMutableContainers
                                                        error:&err];
  if (err) {
    NSLog(@"json解析失败：%@", err);
    return nil;
  }
  return dic;
}

@end
